<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Kafka," />





  <link rel="alternate" href="/atom.xml" title="crossoverJie's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="前言之前写过一篇《从源码分析如何优雅的使用 Kafka 生产者》 ，有生产者自然也就有消费者。

建议对 Kakfa 还比较陌生的朋友可以先看看。

就我的使用经验来说，大部分情况都是处于数据下游的消费者角色。也用 Kafka 消费过日均过亿的消息（不得不佩服 Kakfa 的设计），本文将借助我使用 Kakfa 消费数据的经验来聊聊如何高效的消费数据。">
<meta property="og:type" content="article">
<meta property="og:title" content="分享一些 Kafka 消费数据的小经验">
<meta property="og:url" content="http://crossoverjie.top/2018/11/20/kafka/kafka-consumer/index.html">
<meta property="og:site_name" content="crossoverJie's Blog">
<meta property="og:description" content="前言之前写过一篇《从源码分析如何优雅的使用 Kafka 生产者》 ，有生产者自然也就有消费者。

建议对 Kakfa 还比较陌生的朋友可以先看看。

就我的使用经验来说，大部分情况都是处于数据下游的消费者角色。也用 Kafka 消费过日均过亿的消息（不得不佩服 Kakfa 的设计），本文将借助我使用 Kakfa 消费数据的经验来聊聊如何高效的消费数据。">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c61375484.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c6196e396.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c61ac2377.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c61e93ea2.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c6267f7e3.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c62e08760.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c6368d48a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c639d07b5.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c63bcd72a.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c63e42c09.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c642b1eb2.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c64a28e38.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c64d5033e.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c6503fd42.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c651f08b2.jpg">
<meta property="og:image" content="https://i.loli.net/2019/05/08/5cd1c65727453.jpg">
<meta property="og:updated_time" content="2019-05-07T17:55:19.455Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="分享一些 Kafka 消费数据的小经验">
<meta name="twitter:description" content="前言之前写过一篇《从源码分析如何优雅的使用 Kafka 生产者》 ，有生产者自然也就有消费者。

建议对 Kakfa 还比较陌生的朋友可以先看看。

就我的使用经验来说，大部分情况都是处于数据下游的消费者角色。也用 Kafka 消费过日均过亿的消息（不得不佩服 Kakfa 的设计），本文将借助我使用 Kakfa 消费数据的经验来聊聊如何高效的消费数据。">
<meta name="twitter:image" content="https://i.loli.net/2019/05/08/5cd1c61375484.jpg">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 555390,
      author: 'crossoverJie'
    }
  };
</script>




  <link rel="canonical" href="http://crossoverjie.top/2018/11/20/kafka/kafka-consumer/"/>

  <title> 分享一些 Kafka 消费数据的小经验 | crossoverJie's Blog </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="en">

  








  <div style="display: none;">
    <script src="https://s6.cnzz.com/stat.php?id=1259025147&web_id=1259025147" type="text/javascript"></script>
  </div>





  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">crossoverJie's Blog</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">baller</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            Categories
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            About
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            Tags
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/favourite" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />
            
            photo
          </a>
        </li>
      
        
        <li class="menu-item menu-item-jcsprout">
          <a href="https://crossoverjie.top/JCSprout/#/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-leaf"></i> <br />
            
            JCSprout
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cicada">
          <a href="https://github.com/TogetherOS/cicada" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-github"></i> <br />
            
            cicada
          </a>
        </li>
      
        
        <li class="menu-item menu-item-cim">
          <a href="https://github.com/crossoverjie/cim" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-far fa-comment"></i> <br />
            
            CIM
          </a>
        </li>
      
        
        <li class="menu-item menu-item-vlog">
          <a href="https://space.bilibili.com/42339430" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-youtube"></i> <br />
            
            Vlog
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="#" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            Search
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                分享一些 Kafka 消费数据的小经验
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">Posted on</span>
            <time itemprop="dateCreated" datetime="2018-11-20T00:02:24+08:00" content="2018-11-20">
              2018-11-20
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Kafka/" itemprop="url" rel="index">
                    <span itemprop="name">Kafka</span>
                  </a>
                </span>

                
                
                  , 
                

              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Kafka/Java-进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Java 进阶</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2018/11/20/kafka/kafka-consumer/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/11/20/kafka/kafka-consumer/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          
             <span id="/2018/11/20/kafka/kafka-consumer/" class="leancloud_visitors" data-flag-title="分享一些 Kafka 消费数据的小经验">
               &nbsp; | &nbsp;
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               <span class="post-meta-item-text">visitors </span>
               <span class="leancloud-visitors-count"></span>
              </span>
          

          
              &nbsp; | &nbsp;
              <span class="page-pv">本文总阅读量
              <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
              </span>
          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://i.loli.net/2019/05/08/5cd1c61375484.jpg" alt=""></p>
<h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>之前写过一篇<a href="https://crossoverjie.top/2018/10/11/kafka/kafka-product/">《从源码分析如何优雅的使用 Kafka 生产者》</a> ，有生产者自然也就有消费者。</p>
<blockquote>
<p>建议对 Kakfa 还比较陌生的朋友可以先看看。</p>
</blockquote>
<p>就我的使用经验来说，大部分情况都是处于数据下游的消费者角色。也用 <code>Kafka</code> 消费过日均过亿的消息（不得不佩服 Kakfa 的设计），本文将借助我使用 Kakfa 消费数据的经验来聊聊如何高效的消费数据。</p>
<a id="more"></a>
<h1 id="单线程消费"><a href="#单线程消费" class="headerlink" title="单线程消费"></a>单线程消费</h1><p>以之前生产者中的代码为例，事先准备好了一个 <code>Topic:data-push</code>，3个分区。</p>
<p>先往里边发送 100 条消息，没有自定义路由策略，所以消息会均匀的发往三个分区。</p>
<p>先来谈谈最简单的单线程消费，如下图所示：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c6196e396.jpg" alt=""></p>
<p>由于数据散列在三个不同分区，所以单个线程需要遍历三个分区将数据拉取下来。</p>
<p>单线程消费的示例代码：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c61ac2377.jpg" alt=""></p>
<p>这段代码大家在官网也可以找到：将数据取出放到一个内存缓冲中最后写入数据库的过程。</p>
<blockquote>
<p>先不讨论其中的 offset 的提交方式。</p>
</blockquote>
<p><img src="https://i.loli.net/2019/05/08/5cd1c61e93ea2.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c6267f7e3.jpg" alt=""></p>
<p>通过消费日志可以看出：</p>
<p>取出的 100 条数据确实是分别遍历了三个分区。</p>
<p>单线程消费虽然简单，但存在以下几个问题：</p>
<ul>
<li>效率低下。如果分区数几十上百个，单线程无法高效的取出数据。</li>
<li>可用性很低。一旦消费线程阻塞，甚至是进程挂掉，那么整个消费程序都将出现问题。</li>
</ul>
<h1 id="多线程消费"><a href="#多线程消费" class="headerlink" title="多线程消费"></a>多线程消费</h1><p>既然单线程有诸多问题，那是否可以用多线程来提高效率呢？</p>
<p>在多线程之前不得不将消费模式分为两种进行探讨：消费组、独立消费者。</p>
<p>这两种消费模式对应的处理方式有着很大的不同，所以很有必要单独来讲。</p>
<h2 id="独立消费者模式"><a href="#独立消费者模式" class="headerlink" title="独立消费者模式"></a>独立消费者模式</h2><p>先从<code>独立消费者模式</code>谈起，这种模式相对于消费组来说用的相对小众一些。</p>
<p>看一个简单示例即可知道它的用法：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c62e08760.jpg" alt=""></p>
<blockquote>
<p>值得注意的是：独立消费者可以不设置 group.id 属性。</p>
</blockquote>
<p>也是发送100条消息，消费结果如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c6368d48a.jpg" alt=""></p>
<p>通过 API 可以看出：我们可以手动指定需要消费哪些分区。</p>
<p>比如 <code>data-push</code> Topic 有三个分区，我可以手动只消费其中的 1 2 分区，第三个可以视情况来消费。</p>
<p>同时它也支持多线程的方式，每个线程消费指定分区进行消费。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c639d07b5.jpg" alt=""></p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c63bcd72a.jpg" alt=""></p>
<p>为了直观，只发送了 10 条数据。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c63e42c09.jpg" alt=""></p>
<p>根据消费结果可以看出：</p>
<p>c1 线程只取 0 分区；c2 只取 1 分区；c3 只取 2 分区的数据。</p>
<p>甚至我们可以将消费者多进程部署，这样的消费方式如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c642b1eb2.jpg" alt=""></p>
<p>假设 <code>Topic:data-push</code> 的分区数为 4 个，那我们就可以按照图中的方式创建两个进程。</p>
<p>每个进程内有两个线程，每个线程再去消费对应的分区。</p>
<p>这样当我们性能不够新增 Topic 的分区数时，消费者这边只需要这样水平扩展即可，非常的灵活。</p>
<p>这种自定义分区消费的方式在某些场景下还是适用的，比如生产者每次都将某一类的数据只发往一个分区。这样我们就可以只针对这一个分区消费。</p>
<p>但这种方式有一个问题：可用性不高，当其中一个进程挂掉之后；该进程负责的分区数据没法转移给其他进程处理。</p>
<h2 id="消费组模式"><a href="#消费组模式" class="headerlink" title="消费组模式"></a>消费组模式</h2><p>消费组模式应当是使用最多的一种消费方式。</p>
<p>我们可以创建 N 个消费者实例（<code>new KafkaConsumer()</code>）,当这些实例都用同一个 <code>group.id</code> 来创建时，他们就属于同一个消费组。</p>
<p>在同一个消费组中的消费实例可以收到消息，但一个分区的消息只会发往一个消费实例。</p>
<p>还是借助官方的示例图来更好的理解它。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c64a28e38.jpg" alt=""></p>
<p>某个 Topic 有四个分区 <code>p0 p1 p2 p3</code>，同时创建了两个消费组 <code>groupA，groupB</code>。</p>
<ul>
<li>A 消费组中有两个消费实例 <code>C1、C2</code>。</li>
<li>B 消费组中有四个消费实例 <code>C3、C4、C5、C6</code>。</li>
</ul>
<p>这样消息是如何划分到每个消费实例的呢？</p>
<p>通过图中可以得知：</p>
<ul>
<li>A 组中的 C1 消费了 P0 和 P3 分区；C2 消费 P1、P2 分区。</li>
<li>B 组有四个实例，所以每个实例消费一个分区；也就是消费实例和分区是一一对应的。</li>
</ul>
<p>需要注意的是：</p>
<blockquote>
<p>这里的消费实例简单的可以理解为 <code>new KafkaConsumer</code>，<strong>它和进程没有关系</strong>。</p>
</blockquote>
<hr>
<p>比如说某个 Topic 有三个分区，但是我启动了两个进程来消费它。</p>
<p>其中每个进程有两个消费实例，那其实就相当于有四个实例了。</p>
<p>这时可能就会问 4 个实例怎么消费 3 个分区呢？</p>
<h1 id="消费组自平衡"><a href="#消费组自平衡" class="headerlink" title="消费组自平衡"></a>消费组自平衡</h1><p>这个 Kafka 已经帮我做好了，它会来做消费组里的 <code>Rebalance</code>。</p>
<p>比如上面的情况，3 个分区却有 4 个消费实例；最终肯定只有三个实例能取到消息。但至于是哪三个呢，这点 Kakfa 会自动帮我们分配好。</p>
<p>看个例子，还在之前的 <code>data-push</code> 这个 Topic，其中有三个分区。</p>
<p>当其中一个进程（其中有三个线程，每个线程对应一个消费实例）时，消费结果如下：</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c64d5033e.jpg" alt=""></p>
<p>里边的 20 条数据都被这个进程的三个实例消费掉。</p>
<p>这时我新启动了一个进程，程序和上面那个一模一样；这样就相当于有两个进程，同时就是 6 个实例。</p>
<p>我再发送 10 条消息会发现：</p>
<p>进程1 只取到了分区 1 里的两条数据（之前是所有数据都是进程1里的线程获取的）。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c6503fd42.jpg" alt=""></p>
<hr>
<p>同时进程2则消费了剩下的 8 条消息，分别是分区 0、2 的数据（总的还是只有三个实例取到了数据，只是分别在不同的进程里）。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c651f08b2.jpg" alt=""></p>
<hr>
<p>当我关掉进程2，再发送10条数据时会发现所有数据又被进程1里的三个线程消费了。</p>
<p><img src="https://i.loli.net/2019/05/08/5cd1c65727453.jpg" alt=""></p>
<p>通过这些测试相信大家已经可以看到消费组的优势了。</p>
<blockquote>
<p>我们可以在一个消费组中创建多个消费实例来达到高可用、高容错的特性，不会出现单线程以及独立消费者挂掉之后数据不能消费的情况。同时基于多线程的方式也极大的提高了消费效率。</p>
</blockquote>
<p>而当新增消费实例或者是消费实例挂掉时 <code>Kakfa</code> 会为我们重新分配消费实例与分区的关系就被称为消费组 <code>Rebalance</code>。</p>
<p>发生这个的前提条件一般有以下几个：</p>
<ul>
<li>消费组中新增消费实例。</li>
<li>消费组中消费实例 down 掉。</li>
<li>订阅的 Topic 分区数发生变化。</li>
<li>如果是正则订阅 Topic 时，匹配的 Topic 数发生变化也会导致 <code>Rebalance</code>。</li>
</ul>
<p>所以推荐使用这样的方式消费数据，同时扩展性也非常好。当性能不足新增分区时只需要启动新的消费实例加入到消费组中即可。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>本次只分享了几个不同消费数据的方式，并没有着重研究消费参数、源码；这些内容感兴趣的话可以在下次分享。</p>
<p>文中提到的部分源码可以在这里查阅：</p>
<p><a href="https://github.com/crossoverJie/JCSprout" target="_blank" rel="external">https://github.com/crossoverJie/JCSprout</a></p>
<p><strong>欢迎关注公众号一起交流：</strong></p>

      
    </div>

    <div>
      
        
<div id="wechat_subscriber" style="display: block； padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/weixinfooter1.jpg" alt="crossoverJie wechat" style="width: 200px; max-width: 100%;"/>
    <div>我很有眼光！</div>
</div>

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>请我吃🍗</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/weixin-reward-image.jpg" alt="crossoverJie WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/alipay-reward-image.jpg" alt="crossoverJie Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Kafka/" rel="tag">#Kafka</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/15/wheel/cicada6/" rel="next" title="设计一个可拔插的 IOC 容器">
                <i class="fa fa-chevron-left"></i> 设计一个可拔插的 IOC 容器
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/26/guava/guava-bloom-filter/" rel="prev" title="如何判断一个元素在亿级数据中是否存在？">
                如何判断一个元素在亿级数据中是否存在？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  <p>热评文章</p>
  <div class="ds-top-threads" data-range="weekly" data-num-items="4"></div>


          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            Overview
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/crossoverjie.jpg"
               alt="crossoverJie" />
          <p class="site-author-name" itemprop="name">crossoverJie</p>
          <p class="site-description motion-element" itemprop="description">You never know what you can do till you try.</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">116</span>
              <span class="site-state-item-name">posts</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">45</span>
                <span class="site-state-item-name">categories</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">109</span>
                <span class="site-state-item-name">tags</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/crossoverJie" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/users/e2d07947c112/latest_articles" target="_blank" title="简书">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  简书
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/576d4aaf7db2a20054ea4544" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-bookmark"></i>
                  
                  掘金
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/crossoverJie" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuchong.me" title="Jark's Blog" target="_blank">Jark's Blog</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://tengj.top" title="嘟嘟独立博客" target="_blank">嘟嘟独立博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://yemengying.com/" title="Giraffe Home" target="_blank">Giraffe Home</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.jamespan.me/" title="潘小鶸(ruò)" target="_blank">潘小鶸(ruò)</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://fangjian0423.github.io/" title="Format's Notes" target="_blank">Format's Notes</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://yuzhouwan.com/" title="Benedict Jin" target="_blank">Benedict Jin</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://blog.didispace.com/" title="程序猿DD" target="_blank">程序猿DD</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://blog.52itstyle.vip/" title="小柒博客" target="_blank">小柒博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://cmsblogs.com/" title="Java技术驿站" target="_blank">Java技术驿站</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://vim.ink/" title="vim 教程网" target="_blank">vim 教程网</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.jitwxs.cn" title="jitwxs" target="_blank">jitwxs</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.javaboy.org" title="江南一点雨" target="_blank">江南一点雨</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.liangsonghua.me" title="松花皮蛋的黑板报" target="_blank">松花皮蛋的黑板报</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.fi-ads.com" title="Future iDeal" target="_blank">Future iDeal</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#单线程消费"><span class="nav-number">2.</span> <span class="nav-text">单线程消费</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#多线程消费"><span class="nav-number">3.</span> <span class="nav-text">多线程消费</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#独立消费者模式"><span class="nav-number">3.1.</span> <span class="nav-text">独立消费者模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#消费组模式"><span class="nav-number">3.2.</span> <span class="nav-text">消费组模式</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#消费组自平衡"><span class="nav-number">4.</span> <span class="nav-text">消费组自平衡</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">5.</span> <span class="nav-text">总结</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2016 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">crossoverJie</span>
</div>

<div class="powered-by">
  Powered by <a class="theme-link" href="http://hexo.io">Hexo</a>
</div>

<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

<div class="busuanzi-count">

  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv"><i class="fa fa-user"></i><span class="busuanzi-value" id="busuanzi_value_site_uv"></span>人数</span>
  

  
    <span class="site-pv">您是第<span class="busuanzi-value" id="busuanzi_value_site_pv"></span>位童鞋</span>
  
  
</div>



        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  

    <script type="text/javascript">
      var disqus_shortname = 'crossoverjie';
      var disqus_identifier = '2018/11/20/kafka/kafka-consumer/';
      var disqus_title = "分享一些 Kafka 消费数据的小经验";
      var disqus_url = 'http://crossoverjie.top/2018/11/20/kafka/kafka-consumer/';

      function run_disqus_script(disqus_script){
        var dsq = document.createElement('script');
        dsq.type = 'text/javascript';
        dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/' + disqus_script;
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
      }

      run_disqus_script('count.js');
      
        run_disqus_script('embed.js');
      
    </script>
  




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';                
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });
                            
                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').mousedown(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("Qv6ckEtL1pe3PJD10qoOLKtg-gzGzoHsz", "NXiHFodQfmI8oxkK6IThhjrF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script type="text/javascript" src="/js/src/particle.js" count="50" zindex="-2" opacity="1" color="0,104,183"></script>
</body>
</html>
